package com.ky.manage.activity.indoor;

import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ky.manage.R;
import com.ky.manage.adapter.PicShowAdapter;
import com.ky.manage.base.BaseActivity;
import com.ky.manage.model.response.IndoorCheckItemListResp;
import com.ky.manage.model.response.IndoorMendSecurityDetailResp;
import com.ky.manage.ui.CheckItemView;
import com.ky.manage.utils.ImageLoader.ImageLoaderUtils;
import com.ky.manage.utils.ToastUtils;
import com.ky.manage.utils.ZyUtils;
import com.ky.manage.utils.http.AsyncHttpUtils;
import com.ky.manage.utils.http.BusinessHttpReqUtils;
import com.loopj.android.http.TextHttpResponseHandler;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * 户内整改记录详情页
 */
public class IndoorMendListDetailActivity extends BaseActivity {
    private String mRecordId = "", mIndoorId = "";
    private RefreshLayout refreshLayout;
    private TextView clientNameTv, clientTelTv, addressRegionTv, detailAddressTv, brandTv, idCardTv,
            emailTv, biLuBrandTv, initLevelTv, hiddenDangerLevelTv;
    private ImageView signIv;
    private RecyclerView picListRecyclerView;
    private LinearLayout checkListViewGroup;

    public static void toIndoorMendListDetailPage(BaseActivity baseActivity, String recordId, String indoorId) {
        Intent intent = new Intent(baseActivity, IndoorMendListDetailActivity.class);
        intent.putExtra("recordId", recordId);
        intent.putExtra("indoorId", indoorId);
        baseActivity.toActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_indoor_mend_list_detail;
    }

    @Override
    protected void initView() {
        findView(R.id.back_iv, v -> {
            finish();
        });
        findTextView(R.id.page_title_tv, "检测记录");
        clientNameTv = findView(R.id.client_name_tv);
        clientTelTv = findView(R.id.client_tel_tv);
        brandTv = findView(R.id.brand_name_tv);
        addressRegionTv = findView(R.id.address_region_tv);
        detailAddressTv = findView(R.id.detail_address_tv);
        idCardTv = findView(R.id.id_card_value_tv);
        emailTv = findView(R.id.email_tv);
        biLuBrandTv = findView(R.id.bi_lu_brand_type_tv);
        signIv = findView(R.id.sign_iv);
        picListRecyclerView = findView(R.id.pic_list_view);
        checkListViewGroup = findView(R.id.check_list_ll);
        initLevelTv = findView(R.id.init_level_tv);
        hiddenDangerLevelTv = findView(R.id.hidden_danger_level_tv);
    }

    @Override
    protected void initData() {
        mRecordId = getIntent().getStringExtra("recordId");
        mIndoorId = getIntent().getStringExtra("indoorId");

        refreshLayout = findView(R.id.refreshLayout);
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
        refreshLayout.autoRefresh();
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            reqIndoorMendDetailInfo();
        });
    }

    private void reqIndoorMendDetailInfo() {
        if (!ZyUtils.getInstance().isNetConnected()) {
            refreshLayout.finishRefresh();
            return;
        }
        ZyUtils.getInstance().showLoadingDialog(this, "");
        AsyncHttpUtils.getInstance().get(BusinessHttpReqUtils.SERVICE_DOMAIN + "/appApi/getIndoorMendInfo/" + mRecordId, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                refreshLayout.finishRefresh();
                ZyUtils.getInstance().hideLoadingDialog();
                ToastUtils.showRoundRectToast("获取数据失败：" + responseString);
                ZyUtils.getInstance().insertLog("reqIndoorMendDetailInfo", "onFailure statusCode = "
                        + statusCode + ", responseString = " + responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                refreshLayout.finishRefresh();
                ZyUtils.getInstance().hideLoadingDialog();
                ZyUtils.getInstance().insertLog("reqIndoorMendDetailInfo", "onSuccess statusCode = "
                        + statusCode + ", responseString = " + responseString);
                if (statusCode == 200) {
                    IndoorMendSecurityDetailResp detailResp = BusinessHttpReqUtils.getInstance().parseJsonObj(responseString, IndoorMendSecurityDetailResp.class);
                    if (null != detailResp && detailResp.code == 200) {
                        initDetailInfoView(detailResp.data);
                        BusinessHttpReqUtils.getInstance().requestIndoorCheckItemListInfo(mIndoorId, new TextHttpResponseHandler() {
                            @Override
                            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                                ZyUtils.getInstance().insertLog("getProjectList", "onFailure statusCode = "
                                        + statusCode + ", responseString = " + responseString);
                                ToastUtils.showRoundRectToast("服务器异常，获取检测项目失败");
                            }

                            @Override
                            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                                ZyUtils.getInstance().insertLog("getProjectList", "onSuccess statusCode = "
                                        + statusCode + ", responseString = " + responseString);
                                if (statusCode == 200) {
                                    IndoorCheckItemListResp itemListResp = BusinessHttpReqUtils.getInstance().parseJsonObj(responseString, IndoorCheckItemListResp.class);
                                    if (null != itemListResp && itemListResp.code == 200) {
                                        initCheckListResult(itemListResp.rows);
                                    } else {
                                        ToastUtils.showRoundRectToast("服务器异常，获取检测项目失败");
                                    }
                                } else {
                                    ToastUtils.showRoundRectToast("服务器异常，获取检测项目失败");
                                }
                            }
                        });
                    } else {
                        ToastUtils.showRoundRectToast("服务器异常，请稍候重试");
                    }
                } else {
                    ToastUtils.showRoundRectToast("服务器异常，请稍候重试");
                }
            }
        });
    }

    /**
     * 检测条目列表
     * @param rows
     */
    private void initCheckListResult(List<IndoorCheckItemListResp.CheckItemInfo> rows) {
        checkListViewGroup.removeAllViews();
        if (null != rows && !rows.isEmpty()) {
            for (int i = 0; i < rows.size(); i++) {
                IndoorCheckItemListResp.CheckItemInfo checkItemInfo = rows.get(i);
                CheckItemView checkItemView = new CheckItemView(this);
                checkItemView.setLabelTxt(checkItemInfo.projectName);
                //是否有问题（0是， 1否）
                checkItemView.setStateTxt("0".equals(checkItemInfo.isQuestion) ? "是" : "否");
                checkItemView.setOnClickListener(v -> {
                    IndoorProjectItemInfoActivity.toCheckItemInfoActivity(this, checkItemInfo);
                });
                checkListViewGroup.addView(checkItemView);
            }
        }
    }

    /**
     * 更新详情数据
     * @param detailInfo
     */
    private void initDetailInfoView(IndoorMendSecurityDetailResp.DetailInfo detailInfo) {
        if (null == detailInfo) {
            return;
        }
        clientNameTv.setText(detailInfo.clientName);
        clientTelTv.setText(detailInfo.clientTel);
        brandTv.setText(detailInfo.brandName);
        addressRegionTv.setText(TextUtils.isEmpty(detailInfo.addressList) ? "" :
                detailInfo.addressList.replace(",", ""));
        detailAddressTv.setText(detailInfo.detailedAddress);
        idCardTv.setText(detailInfo.numberId);
        emailTv.setText(detailInfo.email);
        biLuBrandTv.setText(detailInfo.furnaceCode);

        initLevelTv.setText(detailInfo.getShowInitLevel());
        initLevelTv.setTextColor(getStateTxtColor(detailInfo.initLevel));
        hiddenDangerLevelTv.setText(detailInfo.getShowHiddenDangerLevel());
        hiddenDangerLevelTv.setTextColor(getStateTxtColor(detailInfo.hiddenDangerLevel));

        if (!TextUtils.isEmpty(detailInfo.signPic)) {
            ImageLoaderUtils.loadImage(this, detailInfo.signPic, signIv);
        }

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        picListRecyclerView.setLayoutManager(gridLayoutManager);
        PicShowAdapter picShowAdapter = new PicShowAdapter(R.layout.layout_pic_show_item,
                null == detailInfo.docList ? new ArrayList<>() : detailInfo.docList);
        picListRecyclerView.setAdapter(picShowAdapter);
        picShowAdapter.notifyDataSetChanged();
    }

    private int getStateTxtColor(String level) {
        if ("1".equals(level)) {
            return Color.parseColor("#D60000");
        } else if ("2".equals(level)) {
            return Color.parseColor("#D66A00");
        }
        return Color.parseColor("#00D619");
    }
}